package com.training.persistence.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.training.persistence.entity.Player;

@Repository(value="playerDao")
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public class PlayerDaoImpl implements PlayerDao, Serializable {

	private static final long serialVersionUID = 1L;
	
	@Autowired
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Player savePlayer(Player player) {
		this.getSession().save(player);
		return player;
	}

	public Player updatePlayer(Player player) {
		this.getSession().saveOrUpdate(player);
		return player;
	}

	public List<Player> findAllPlayers() {
		return this.getSession().createQuery("from Player").list();
	}

	public Player findPlayerById(Long id) {
		return null;
	}

	public Player findPlayerByUserName(String userName) {
		List<Player> players = this.getSession()
				.createQuery("from Player p where p.userName = :userName")
				.setString("userName", userName).list();
		if (players.isEmpty()) {
			return null;
		} else {
			return players.get(0);
		}
	}

	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	public Player findPlayerByUserNameAndPassword(String userName,
			String password) {
		List<Player> players = this
				.getSession()
				.createQuery(
						"from Player p where p.userName = :userName AND p.password = :password")
				.setString("userName", userName)
				.setString("password", password).list();
		if (players.isEmpty()) {
			return null;
		} else {
			return players.get(0);
		}
	}

}
